package middleware

import (
	"github.com/gin-gonic/gin"
	"konglu-pay/common/response"
	"konglu-pay/global"
	"log"
	"runtime/debug"
)

func RecoverError(c *gin.Context) {
	defer func() {
		if r := recover(); r != nil {
			log.Printf("panic: %v\n", r)
			debug.PrintStack()
			global.Log.Errorf("gin global intercept request: %s，error: %v", c.FullPath(), r)
			response.FailWithMsg(c, errToString(r))
		}
	}()
	c.Next()
}

func errToString(r any) string {
	switch v := r.(type) {
	case error:
		return v.Error()
	default:
		return r.(string)
	}
}

func RecoverNotFound(c *gin.Context) {
	response.FailWithMsg(c, "接口不存在")
}
